package cn.xfdzx.android.apps.shop.activity.ruzhu;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.MainActivity;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.ApplyShopInBeen;
import cn.xfdzx.android.apps.shop.bean.BankCardBeen;
import cn.xfdzx.android.apps.shop.bean.EleContractMakeBeen;
import cn.xfdzx.android.apps.shop.bean.ShopIn2Been;
import cn.xfdzx.android.apps.shop.bean.ShopIn3Been;
import cn.xfdzx.android.apps.shop.bean.UploadImgBeen;
import cn.xfdzx.android.apps.shop.contract.ApplyShopInContract;
import cn.xfdzx.android.apps.shop.presenter.ApplyShopInPresenter;
import cn.xfdzx.android.apps.shop.presenter.ShopInPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.GlideEngine;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.util.UtilsLog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;
import static cn.xfdzx.android.apps.shop.apps.Constants.START_CODE;

public class XFDShopInBankNumActivity extends BaseMvpActivity<ApplyShopInPresenter> implements ApplyShopInContract.View {

    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_add_logo)
    ImageView ivAddLogo;
    @BindView(R.id.ett_card_num)
    EditText ettCardNum;
    @BindView(R.id.ett_card_name)
    EditText ettCardName;
    @BindView(R.id.ett_card_from_bank)
    EditText ettCardFromBank;
    @BindView(R.id.ett_card_zhi_bank)
    EditText ettCardZhiBank;
    @BindView(R.id.cb_is_select)
    CheckBox cbIsSelect;

    private boolean is_ivAddLogo = false;

    private Context mContext;
    protected Handler handler = new Handler();
    private RelativeLayout.LayoutParams item_bar;
    //sign_status,bd_content
    private String offline_shop_name = "", store_name = "", store_master = "", store_qualifications_img = "", store_category = "", store_address = "", store_phone = "", store_qualifications_num = "", store_qualifications_name = "", store_qualifications_expire = "", idcard_back_img = "", idcard_front_img = "", qs_img = "", bank_card = "", bank_open_name = "", bank_name = "", bank_branch = "", bd_name = "", bd_phone = "", sign_status = "", bd_content = "", inv_code = "", lat = "", lng = "", store_logo = "", whole_address = "", category_id = "", store_current_address = "", intro = "", salecate = "", front_door_photo = "", in_store_photo = "";

    private String store_num, contract_year, card_code, bank_image = "";
    private ShopIn3Been shopIn3Been;
    private Gson gson = new Gson();

    @Override
    public int getLayoutId() {
        return R.layout.activity_xfdshop_in_bank_num;
    }

    @Override
    public void initView() {
        initHigh();
        mContext = XFDShopInBankNumActivity.this;
        StatusBarUtil.setLightStatusBar(this, false, true);
        mPresenter = new ApplyShopInPresenter();
        mPresenter.attachView(this);

        offline_shop_name = getIntent().getStringExtra("offline_shop_name");
        store_name = getIntent().getStringExtra("store_name");
        store_master = getIntent().getStringExtra("store_master");
        store_qualifications_img = getIntent().getStringExtra("store_qualifications_img");
        store_category = getIntent().getStringExtra("store_category");
        store_address = getIntent().getStringExtra("store_address");
        store_qualifications_num = getIntent().getStringExtra("store_qualifications_num");
        store_qualifications_name = getIntent().getStringExtra("store_qualifications_name");
        store_qualifications_expire = getIntent().getStringExtra("store_qualifications_expire");
        store_logo = getIntent().getStringExtra("store_logo");
        category_id = getIntent().getStringExtra("category_id");
        whole_address = getIntent().getStringExtra("whole_address");
        store_current_address = getIntent().getStringExtra("store_current_address");
        intro = getIntent().getStringExtra("intro");
        salecate = getIntent().getStringExtra("salecate");
        front_door_photo = getIntent().getStringExtra("front_door_photo");
        in_store_photo = getIntent().getStringExtra("in_store_photo");
        bd_content = getIntent().getStringExtra("bd_content");
        inv_code = getIntent().getStringExtra("inv_code");
        lng = getIntent().getStringExtra("lng");
        lat = getIntent().getStringExtra("lat");

        store_phone = getIntent().getStringExtra("store_phone");
        idcard_back_img = getIntent().getStringExtra("idcard_back_img");
        idcard_front_img = getIntent().getStringExtra("idcard_front_img");
        qs_img = getIntent().getStringExtra("qs_img");
        bd_name = getIntent().getStringExtra("bd_name");
        bd_phone = getIntent().getStringExtra("bd_phone");
        contract_year = getIntent().getStringExtra("contract_year");
        store_num = getIntent().getStringExtra("store_num");
        card_code = getIntent().getStringExtra("card_code");

        if (store_category.equals("0")) {
            llState.setBackgroundColor(getResources().getColor(R.color.color_FB9129));
            rlTitle.setBackgroundColor(getResources().getColor(R.color.color_FB9129));
            tvSubmit.setBackgroundResource(R.drawable.dfb9129_bg_r8);
        } else {

            llState.setBackgroundColor(getResources().getColor(R.color.color_02C557));
            rlTitle.setBackgroundColor(getResources().getColor(R.color.color_02C557));
            tvSubmit.setBackgroundResource(R.drawable.d02c557_bg_r8);
        }
//回显
        setText();
    }


    private void setText() {
        if (null == UtilsData.getPreference(this, "ruzhu").getString("shopIn3")) {
            shopIn3Been = new ShopIn3Been();
        } else {
            RoundedCorners roundedCorners = new RoundedCorners(10);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
            shopIn3Been = gson.fromJson(UtilsData.getPreference(this, "ruzhu").getString("shopIn3"), ShopIn3Been.class);

            if (!shopIn3Been.bank_image.isEmpty()) {
                is_ivAddLogo = true;
                bank_image = shopIn3Been.bank_image;
                Glide.with(mContext).load(bank_image).apply(options.transform(new CenterCrop(), roundedCorners)).into(ivAddLogo);
            }


            ettCardNum.setText(shopIn3Been.bank_card);
            ettCardName.setText(shopIn3Been.bank_open_name);
            ettCardFromBank.setText(shopIn3Been.bank_name);
            ettCardZhiBank.setText(shopIn3Been.bank_branch);

        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        shopIn3Been.bank_image = bank_image;
        shopIn3Been.bank_card = ettCardNum.getText().toString().trim();
        shopIn3Been.bank_open_name = ettCardName.getText().toString().trim();
        shopIn3Been.bank_name = ettCardFromBank.getText().toString().trim();
        shopIn3Been.bank_branch = ettCardZhiBank.getText().toString().trim();

        UtilsData.getPreference(this, "ruzhu").put("shopIn3", gson.toJson(shopIn3Been));
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @Override
    public void showLoading() {
        ProgressDialog.getInstance().show(this);
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @OnClick({R.id.iv_back, R.id.tv_submit, R.id.iv_add_logo})
    public void Onclick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_add_logo:
                selectImage();
                break;
            case R.id.tv_submit:
                if (!is_ivAddLogo) {
                    Toast.makeText(mContext, "请上传银行卡照片", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (ettCardNum.getText().toString().trim().isEmpty()) {
                    Toast.makeText(mContext, "请填写银行卡号", Toast.LENGTH_SHORT).show();
                    return;
                }
                bank_card = ettCardNum.getText().toString().trim();
                if (ettCardName.getText().toString().trim().isEmpty()) {
                    Toast.makeText(mContext, "请填写开户名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!ettCardName.getText().toString().trim().equals(bd_name)) {
                    Toast.makeText(mContext, "开户人姓名与店铺所有人姓名不一致！", Toast.LENGTH_SHORT).show();
                    return;
                }
                bank_open_name = ettCardName.getText().toString().trim();
                if (ettCardFromBank.getText().toString().trim().isEmpty()) {
                    Toast.makeText(mContext, "请填写开户银行", Toast.LENGTH_SHORT).show();
                    return;
                }
                bank_name = ettCardFromBank.getText().toString().trim();
                if (ettCardZhiBank.getText().toString().trim().isEmpty()) {
                    Toast.makeText(mContext, "请填写银行支行", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (cbIsSelect.isChecked()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("contract_year", contract_year);
                    map.put("store_num", store_num);
                    map.put("telephone", bd_phone);
                    map.put("card_name", bd_name);
                    map.put("card_code", card_code);
                    map.put("customer_name", store_name);
                    map.put("orgnizationCode", store_qualifications_num);
                    map.put("orgnizationMster", store_master);
                    map.put("customer_address", store_address);
                    map.put("bank_name", bank_name);
                    map.put("bank_code", bank_card);
                    mPresenter.eleContractMake(contract_year, store_num, bd_phone, bd_name, card_code, store_name, store_qualifications_num, store_master, store_address, bank_name, bank_card);
                } else {
                    bank_branch = ettCardZhiBank.getText().toString().trim();
                    mPresenter.applySubmit(card_code,offline_shop_name, whole_address, inv_code, lat, lng, store_name, store_master, store_qualifications_img, store_category, store_address, store_phone, store_qualifications_num, store_qualifications_name, store_qualifications_expire, idcard_back_img, idcard_front_img, qs_img, bank_card, bank_open_name, bank_name, bank_branch, bd_name, bd_phone, sign_status, bd_content, store_logo, category_id, store_current_address, intro, salecate, front_door_photo, in_store_photo);
                }
                break;
        }
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onApplySubmitSuccess(ApplyShopInBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            UtilsData.getPreference(this, "login").put("is_store", 1);
            Toast.makeText(this, "申请成功", Toast.LENGTH_SHORT).show();
            UtilsData.getPreference(this, "ruzhu").remove("shopIn1");
            UtilsData.getPreference(this, "ruzhu").remove("shopIn2");
            UtilsData.getPreference(this, "ruzhu").remove("shopIn3");
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBankCardSuccess(BankCardBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            ettCardNum.setText(bean.getData().getBankCardNo());
            ettCardFromBank.setText(bean.getData().getBankName());

        } else {
            Toast.makeText(mContext, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onEleContractMakeSuccess(EleContractMakeBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Intent intent = new Intent(this, WebActivity.class);
            intent.putExtra("url", bean.getData().getShortUrl());
            startActivityForResult(intent, START_CODE);

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    public void selectImage() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage()).maxSelectNum(1)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .minSelectNum(1).imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)
                .minimumCompressSize(1000)
                .compressQuality(60)
                .isCamera(true)
                .previewImage(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // onResult Callback
                        if (result.size() != 0) {
                            UtilsLog.error("dizhi", result.get(0).getCompressPath());
//                                    new File(result.get(0).getPath())
//                                    mPresenter.upload(new File(result.get(0).getPath()));
                            showLoading();
                            upLoadFiles(Constants.BASE_URL + "/addons/shimmer_liveshop/index.php/api/6/3/plugin/merch/common/apply/uploadImg", new File(result.get(0).getCompressPath()), new XFDShopInActivity.ConnectListener() {
                                @Override
                                public void connectSuccess(String result) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();
                                            try {
                                                Gson gson = new Gson();
                                                UploadImgBeen uploadImgBeen = gson.fromJson(result, UploadImgBeen.class);
                                                if (uploadImgBeen.getErrno().equals("200")) {

                                                    RoundedCorners roundedCorners = new RoundedCorners(10);
                                                    //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                                                    RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
                                                    bank_image = uploadImgBeen.getData().getSrc();
                                                    Glide.with(mContext).load(bank_image).apply(options.transform(new CenterCrop(), roundedCorners)).into(ivAddLogo);
                                                    mPresenter.idCardSubmit(bank_image);
                                                    is_ivAddLogo = true;


                                                } else {
                                                    Toast.makeText(mContext, uploadImgBeen.getMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            } catch (Exception e) {
                                                Toast.makeText(mContext, "上传失败", Toast.LENGTH_SHORT).show();

                                            }
                                        }
                                    });

                                }

                                @Override
                                public void connectFailed(String error) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();

                                        }
                                    });
                                }
                            });
                        }
                    }

                    @Override
                    public void onCancel() {
                        // onCancel Callback
                    }
                });
    }


    public void upLoadFiles(final String url, File file, final XFDShopInActivity.ConnectListener connectListener) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY).connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        multipartBodyBuilder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(url);// 添加URL地址
        RequestBuilder.post(requestBody);
        RequestBuilder.addHeader("Authori-zation", "Bearer " + APP_TOKEN);
        Request request = RequestBuilder.build();

        final Call call = okHttpClient.newCall(request);
        //异步get请求
        call.enqueue(new Callback() {
                         @Override
                         public void onFailure(Call call, IOException e) {
                             connectListener.connectFailed(e.toString());
                             UtilsLog.error("错误", e.toString());
                         }

                         @Override
                         public void onResponse(Call call, Response response) throws IOException {
                             String result = response.body().string();
                             connectListener.connectSuccess(result);
                             UtilsLog.error("成功", result);
                         }
                     }
        );
    }


    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == START_CODE) {
            if (resultCode == RESULT_OK) {
                bank_branch = ettCardZhiBank.getText().toString().trim();
                mPresenter.applySubmit(card_code,offline_shop_name, whole_address, inv_code, lat, lng, store_name, store_master, store_qualifications_img, store_category, store_address, store_phone, store_qualifications_num, store_qualifications_name, store_qualifications_expire, idcard_back_img, idcard_front_img, qs_img, bank_card, bank_open_name, bank_name, bank_branch, bd_name, bd_phone, sign_status, bd_content, store_logo, category_id, store_current_address, intro, salecate, front_door_photo, in_store_photo);
            }
        }
    }
}
